package fr.mma.livraison.channel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.gson.Gson;

import fr.mma.livraison.channel.dao.ChannelDao;
import fr.mma.livraison.channel.persistance.Channel;

public class TokenServlet extends HttpServlet {

	/**	 */
	private static final long serialVersionUID = 5289622897597411472L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		final String identifiant = req.getParameter("id");
		if (StringUtils.isNumeric(identifiant)) {
			final Gson gson = new Gson();
			final ChannelDao dao = new ChannelDao();
			Channel channel = dao.getOrCreate(Long.valueOf(identifiant));
			UUID id = UUID.randomUUID();
			ChannelService channelService = ChannelServiceFactory.getChannelService();
			String token = channelService.createChannel(id.toString());
			if(channel.getChannelKeyList() == null){
				channel.setChannelKeyList(new ArrayList<String>());
			}
			channel.getChannelKeyList().add(id.toString());
			resp.setContentType("application/json");
			resp.getWriter().println(gson.toJson(token));
			dao.save(channel);
		}
	}

}
